define(['./../initial', './../directive/prjSummaryPopup', './project'], function() {
    var app = angular.module('App.home');
    app.factory('PublicMap', ['$rootScope', '$compile', 'Project',
        function($rootScope, $compile, Project) {
            var map = L.Map.extend({
                mapSource: '天地图',
                prjMarkerLayer: null, //存放prj marker的layer
                editableLayers: null
            });

            map.prototype.loadPublicMap = function() {
                var map = this;
                var source = window.localStorage.getItem('preferMap');
                source = source || "天地图";
                map.mapSource = source;
                var layers = [];
                var tianMapLayers = L.layerGroup([L.tileLayer('http://{s}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}', {
                    attribution: '&copy; <a target="_blank" href="http://www.chinaonmap.com/map/index.html">天地图</a>',
                    subdomains: ['t2', 't3', 't4', 't5', 't6'],
                    detectRetina: true,
                    reuseTiles: true
                }), L.tileLayer('http://{s}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}', {
                    attribution: '&copy; <a target="_blank" href="http://www.chinaonmap.com/map/index.html">天地图</a>',
                    subdomains: ['t2', 't3', 't4', 't5', 't6'],
                    detectRetina: true,
                    reuseTiles: true
                })]);
                var overlay = L.tileLayer('http://{s}.tianditu.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}', {
                    attribution: '&copy; <a  target="_blank" href="http://www.chinaonmap.com/map/index.html">天地图</a>',
                    detectRetina: true,
                    reuseTiles: true,
                    subdomains: ['t2', 't3', 't4', 't5', 't6'],
                });
                var tianMapSatelliteLayers = L.layerGroup([L.tileLayer('http://{s}.tianditu.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}', {
                    attribution: '&copy; <a target="_blank" href="http://www.chinaonmap.com/map/index.html">天地图</a>',
                    detectRetina: true,
                    reuseTiles: true,
                    subdomains: ['t2', 't3', 't4', 't5', 't6'],
                }), overlay]);



                var gaodeMapLayers = L.layerGroup([L.tileLayer('http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', {
                    attribution: '',
                    detectRetina: true,
                    reuseTiles: true
                })]);
                var baseMaps = {
                    "高德地图": gaodeMapLayers,
                    "天地图": tianMapLayers,
                    "天地图影像": tianMapSatelliteLayers
                };

                map.addLayer(baseMaps[source]);

                //var layersControl = L.control.layers(baseMaps).addTo(map);
                //map.addDrawControl();

                map.attributionControl.setPrefix('');
                map.prjMarkerLayer = new L.LayerGroup().addTo(map);

            };

            map.prototype.addDrawControl = function() {
                var m = this;
                var editableLayers = new L.FeatureGroup();
                m.addLayer(editableLayers);
                m.editableLayers = editableLayers;

                var drawControl = new L.Control.Draw({
                    position: 'bottomright',
                    draw: {
                        polyline: {
                            shapeOptions: {
                                color: '#F02B88',
                                weight: 5,
                                opacity: 0.8
                            },
                            metric: true
                        },
                        polygon: {
                            allowIntersection: false,
                            showArea: true,
                            metric: true,
                            drawError: {
                                color: '#b00b00',
                                timeout: 1000
                            },
                            shapeOptions: {
                                color: '#3572CC',
                                opacity: 0.98,
                                fillOpacity: 0.8
                            }
                        },
                        rectangle: false,
                        circle: false,
                        marker: false
                    },
                    edit: {
                        featureGroup: editableLayers, //REQUIRED!!
                        remove: true,
                        edit: true
                    }
                }).addTo(m);
                map.setView(point, zoom);
                m.on('draw:created', function(e) {
                    var type = e.layerType,
                        layer = e.layer,
                        info = e.layerInfo;

                    var center = layer.getBounds().getCenter();
                    m.editableLayers.addLayer(layer);
                    layer.bindPopup('<span class="auto-point-popup-span">' + info + "</span>", {
                        closeButton: false,
                        offset: new L.Point(0, 3)
                    }).openPopup(center);
                });
            };

            map.prototype.addPrjs = function(prjs) {
                var map = this;
                if (prjs) {
                    map.prjMarkerLayer.clearLayers();
                    prjs.forEach(function(prj, index, array) {
                        map.addPrj(prj, index, array);
                    });
                }
            };
            map.prototype.addPrj = function(prj, index, array) {
                var map = this;
                var offset = [0, 0];
                var offsets = {
                    '高德地图': [0, 0],
                    '天地图': [0.00205972005050015, -0.00445783138300726],
                    '天地图影像': [0.00205972005050015, -0.00445783138300726]
                };
                offset = offsets[map.mapSource];
                var center = [prj.center.lat + offset[0], prj.center.lng + offset[1]];
                prj.marker = L.marker(center, {
                    icon: L.AwesomeMarkers.icon({
                        icon: 'hh',
                        prefix: 'i',
                        markerColor: 'red',
                        iconColor: '#fff',
                        extraClasses: '  fa fa-home prj-marker '
                    })
                });

                // (function bindPopup(prj) {
                //     var div = document.createElement('div');
                //     var index = $rootScope.projects.indexOf(prj);
                //     div.setAttribute('data-prj-summary-popup', '');
                //     div.setAttribute('data-prj', 'projects[' + index.toString() + ']');
                //     var element = angular.element(div);
                //     $compile(element)($rootScope);
                //     prj.marker.bindPopup(div);
                // })(prj);

                map.prjMarkerLayer.addLayer(prj.marker);

                if (prj.monitorPoints.length === 0) {
                    console.log('%s 没有配置任何监测点', prj.name);
                    array.splice(index, 1);
                } else {
                    prj.monitorPoints[0].active = true;
                    prj.monitorPoints[0].locationPoints[0].active = true;
                    prj.marker.on('click', function(e) {
                        var marker = e.target;
                        e.target.openPopup();
                    });
                }

                // prj.marker.on('mouseout', function(e) {
                //     //e.target.closePopup();
                // });
            };
            return map;
        }
    ]);
});
